/**
 * 系统管理  角色管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <NoPermission
      v-if="!authFilter(permissionObj, 'index')">
    </NoPermission>

    <div v-else>

      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="formInline" class="user-search">

        <el-form-item label="搜索：">
          <el-input size="small" v-model="formInline.roleName" placeholder="输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit(null,{},true)"
                     v-if="authFilter(permissionObj, 'add')">
            添加
          </el-button>
        </el-form-item>
      </el-form>
      <!--列表-->
      <div class="relative">
        <el-table
          :header-cell-style="{'font-weight': '600', 'color':'#333'}"
          size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
          <el-table-column align="center" type="selection" width="60">
          </el-table-column>
          <el-table-column align="center" sortable prop="roleName" label="角色名称" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="remark" label="备注" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="createTime" label="创建时间" min-width="120">
            <template slot-scope="scope">
              <div>{{scope.row.createTime|timestampToDay}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" sortable prop="creatUser" label="创建用户" min-width="140">
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right" :min-width="operaWidth">
            <template slot-scope="scope">
              <el-button size="mini"
                :disabled="!scope.row.editable"
                @click="handleEdit(scope.$index, scope.row, false)"
                         v-if="authFilter(permissionObj, 'update')">编辑</el-button>
              <el-button size="mini" type="danger"
                :disabled="!scope.row.editable||scope.row.pRid==0"
                @click="deleteColumn(scope.$index, scope.row)"
                         v-if="authFilter(permissionObj, 'delete')">
                删除
              </el-button>
             <!-- <el-button
                size="mini"
                type="success"
                :disabled="!scope.row.editable"
                @click="menuAccess(scope.$index, scope.row)">菜单权限</el-button> -->
              <el-button
                size="mini"
                type="success"
                :disabled="!scope.row.editable"
                @click="dataAccess(scope.$index, scope.row)"
                v-if="authFilter(permissionObj, 'permissions')">
                功能权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      </div>

    </div>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="35%" @click='closeDialog("edit")'
               style="margin-left: 200px;">
      <el-form label-width="100px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input size="small" v-model="editForm.roleName" auto-complete="off" placeholder="请输入角色名称"
          :maxlength="100" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input size="small" v-model="editForm.remark" auto-complete="off" placeholder="请输入备注"
                    :autosize="{ minRows: 3, maxRows: 4}"
                    type="textarea" :maxlength="400" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 菜单权限 -->
    <el-dialog title="菜单权限" :visible.sync="menuAccessshow" width="30%" @click='closeDialog("perm")'>
      <el-tree ref="tree" default-expand-all="" :data="RoleRight" :props="RoleRightProps" :default-checked-keys="checkmenu" node-key="id" show-checkbox>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="menuPermSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 功能权限 -->
    <el-dialog title="功能权限" :visible.sync="dataAccessshow" width="70%" @click='closeDialog("auth")'
               style="margin-left: 200px;">
      <div
        class="jurisdiction-content">
        <div class="jurisdiction-content-checkbox fs14 color66 scrollBar">
          <el-tree
            :data="roleAuthList"
            ref="treeAuthority"
            :indent="0"
            :expand-on-click-node="false"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍后..."
            :default-checked-keys="checkUserAuth"
            default-expand-all>
              <span
                slot-scope="{ node }"
                :class="{ 'node-label': node.level == 1 || node.level == 2,'common-node-label': node.data.id === 1}">
                {{ node.label }}
              </span>
          </el-tree>
        </div>
      </div>
      <!--      <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" :default-checked-keys="checkmenu" node-key="id" show-checkbox>-->
      <!--      </el-tree>-->
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("auth")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="menuAuthSave">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '../../components/Pagination'
import {mapGetters} from "vuex";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      menuAccessshow: false, //控制数据权限显示与隐藏
      title: '添加',
      isAdd: false,
      editForm: {
        rid: '',
        remark: '',
        roleName: '',
        createTime: null,
        creatUser: '',
      },
      // rules 表单验证
      rules: {
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      formInline: {
        page: 1,
        pagenum: 10,
        roleName: '',
      },
      // 删除
      seletedata: {
        ids: '',
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      // 数据权限
      RoleRight: [],
      RoleRightProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      rid: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      //功能权限
      dataAccessshow: false, //控制功能权限显示与隐藏
      roleAuthList: [],
      checkUserAuth: [], // 默认选中
      defaultProps: {
        children: 'children',
        label: 'title'
      },
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  watch: {},
  computed: {
    ...mapGetters(['roleInfo', 'userAuthList', 'userInfo']),
    permissionObj(){
      if(this.userAuthList&&this.userAuthList.length>0){
        return this.authListFilter(this.userAuthList,'customManagement', 'role')
      }
    },
    // 操作列表宽度
    operaWidth(){
      const vm = this
      const minWidth = 120
      const len = vm.authFilterLen(this.permissionObj, 'update', 'delete', 'permissions').length
      return len > 0 ? vm.multiply(len,90) : minWidth
    }
  },

  /**
   * 创建完毕
   */

  created() {
    const vm = this;
    vm.getData(vm.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */

  methods: {
    // 获取角色列表
    getData(parameter) {
      const vm = this;
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      vm.loading = true
      //角色分级
      parameter = {
        ...parameter,
        rid: vm.roleInfo.rid
      }
      vm.apiUrl.roleList(parameter,"POST")
        .then(res => {
          vm.loading = false
          const { data:{list=[],totalnum},code, msg } = res
          if (code != 0) {
            vm.$message({
              type: 'error',
              message: msg
            })
          } else {
            vm.listData = list
            // 分页赋值
            vm.pageparm.currentPage = vm.formInline.page
            vm.pageparm.pageSize = vm.formInline.pagenum
            vm.pageparm.total = totalnum
          }
        })
    },
    // 分页插件事件
    callFather(parm) {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: parm.currentPage,
        pagenum: parm.pageSize
      }
      vm.getData(vm.formInline)
    },
    // 搜索事件
    search() {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: 1
      }
      vm.getData(vm.formInline)
    },
    //显示编辑界面
    handleEdit: function(index, row, isAdd) {
      const vm = this;
      vm.editFormVisible = true
      vm.isAdd = isAdd
      vm.title =  (vm.isAdd ? '添加角色' : '修改角色');
      if (!vm.isAdd) {
        vm.editForm = {
          ...row
        }
      } else {
        vm.editForm = {}
        vm.editForm = {
          ...vm.editForm,
          createTime: new Date().getTime(),
        }
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      const vm = this;
      vm.$refs[editData].validate(valid => {
        if (valid) {
          vm.openFullScreen();
          let request = null
          if(vm.isAdd){
            vm.editForm = {
              ...vm.editForm,
              creatUser: vm.userInfo.userName,
              pRid: vm.roleInfo.rid,
            }
            request = vm.apiUrl.roleAdd(vm.editForm,"POST")
          } else {
            request = vm.apiUrl.roleEdit(vm.editForm,"POST")
          }
          request.then(res => {
              vm.closeFullScreen(vm.openFullScreen());
              vm.editFormVisible = false
              const { code,msg } = res;
              if (code != 0) {
                vm.showMessageMin({
                  type: 'error',
                  message: msg
                })
              } else {
                vm.showMessageMin({
                  type: 'success',
                  message: '角色保存成功！'
                })
                vm.getData(vm.formInline)
              }
            })
        } else {
          return false
        }
      })
    },
    // 删除角色
    deleteColumn(index, row) {
      const vm = this;
      vm.$confirm('确定要删除吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          vm.openFullScreen();
          vm.apiUrl.roleDelete({
            rid: row.rid
          },"POST")
            .then(res => {
              vm.closeFullScreen(vm.openFullScreen());
              const { code,msg } = res;
              if (code != 0) {
                vm.showMessageMin({
                  type: 'error',
                  message: msg
                })
              } else {
                vm.showMessageMin({
                  type: 'success',
                  message: '角色已删除！'
                })
                vm.getData(vm.formInline)
              }
            })
        })
        .catch(() => {
          vm.showMessageMin({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 数据权限
    menuAccess: function(index, row) {
      const vm = this;
      vm.openFullScreen();
      let param = {
        type: 'tree',
        rid: vm.rid
      }
      // console.log('param', param)
      vm.apiUrl.authList(param,"POST")
        .then(res => {
          vm.closeFullScreen(vm.openFullScreen());
          const { code,msg,data } = res;
          if (code != 0) {
            vm.showMessageMin({
              type: 'error',
              message: msg
            })
          } else {
            vm.showMessageMin({
              type: 'success',
              message: '获取权限成功'
            })
            vm.menuAccessshow = true
            vm.rid = row.rid
            vm.changemenu(data)
            vm.RoleRight = vm.changeArr(data)
          }
        })
    },
    // 选中菜单
    changemenu(arr) {
      const vm = this;
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      vm.checkmenu = change
    },
    // tree 递归
    changeArr(list) {
      var temptree = [],
        tree = [],
        items = []
      for (var i in list) {
        if (!temptree[list[i].id]) {
          var trow = {
            id: list[i].id,
            pId: list[i].pId,
            name: list[i].name,
            open: list[i].open,
            checked: list[i].checked,
            children: []
          }
          temptree[list[i].id] = trow
          items.push(trow)
        }
        if (list[i].uid > 0) {
          temptree[list[i].id]['children'].push({
            id: list[i].id,
            pId: list[i].pId,
            name: list[i].name,
            open: list[i].open,
            checked: list[i].checked,
            children: []
          })
        }
      }

      for (var j in items) {
        if (temptree[items[j].pId]) {
          temptree[items[j].pId]['children'].push(temptree[items[j].id])
        } else {
          tree.push(temptree[items[j].id])
        }
      }
      temptree = null
      items = null
      return tree
    },
    // 菜单权限-保存
    menuPermSave() {
      const vm = this;
      let parm = {
        rid: vm.rid,
        moduleIds: ''
      }
      let node = vm.$refs.tree.getCheckedNodes()
      let moduleIds = []
      if (node.length != 0) {
        for (let i = 0; i < node.length; i++) {
          moduleIds.push(node[i].id)
        }
        // parm.moduleIds = JSON.stringify(moduleIds)
        parm.moduleIds = moduleIds.join(',')
      }
      vm.openFullScreen();
      vm.apiUrl.authEdit(parm,"POST")
        .then(res => {
          vm.closeFullScreen(vm.openFullScreen());
          const { code,msg } = res;
          if (code != 0) {
            vm.showMessageMin({
              type: 'error',
              message: msg
            })
          } else {
            vm.showMessageMin({
              type: 'success',
              message: '权限保存成功'
            })
            vm.getData(vm.formInline)
            vm.menuAccessshow = false
          }
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      const vm = this;
      if (dialog == 'edit') {
        vm.editFormVisible = false
      } else if (dialog == 'perm') {
        vm.menuAccessshow = false
      } else if (dialog == 'auth') {
        vm.dataAccessshow = false
      }
    },
    // 功能权限
     async dataAccess(index, row) {
      const vm = this;

      vm.openFullScreen();
      vm.apiUrl.authList({
        rid: row.rid,
        type: 'tree'
      },"POST")
        .then(async (res) => {
          vm.closeFullScreen(vm.openFullScreen());
          const { code,msg, data } = res;
          if (code != 0) {
            vm.showMessageMin({
              type: 'error',
              message: msg
            })
          } else {
            vm.checkUserAuth = []
            vm.roleAuthList = data.list || []
            await vm.checkUserAuthArr(vm.roleAuthList)
            // console.log('vm.checkUserAuth', vm.checkUserAuth)
            vm.rid = row.rid
            vm.dataAccessshow = true
            // vm.checkmenu = vm.changemenu(res.data.data)
            // vm.roleAuthList = vm.changeArr(res.data.data)
          }
        })
        .finally(()=>{
          vm.closeFullScreen(vm.openFullScreen());
        })
    },
    // 功能权限-保存
    menuAuthSave() {
      const vm = this;
      let parm = {
        rid: vm.rid,
        authIds: ''
      }
      let node = vm.$refs.treeAuthority.getCheckedNodes()
      let authIds = []
      if (node.length != 0) {
        for (let i = 0; i < node.length; i++) {
          authIds.push(node[i].id)
        }
        // parm.authIds = JSON.stringify(authIds)
        parm.authIds = authIds.join(',')
      }
      // console.log('parm', parm)
      vm.openFullScreen();
      vm.apiUrl.authEdit(parm,"POST")
        .then(res => {
          vm.closeFullScreen(vm.openFullScreen());
          const { code,msg } = res;
          if (code != 0) {
            vm.showMessageMin({
              type: 'error',
              message: msg
            })
          } else {
            vm.showMessageMin({
              type: 'success',
              message: '权限保存成功'
            })
            vm.closeDialog('auth')
            vm.getData(vm.formInline)
          }
        })
    },
    // 递归默认显示选中功能
    checkUserAuthArr(val){
      const vm = this
      if(val&&val.length!=0){
        val.forEach(item =>{
          if(item.check){
            vm.checkUserAuth.push(item.id);
          }
          vm.checkUserAuthArr(item.children);
        })
      }
    }

  }
}
</script>

<style lang="less" scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}

/* 功能权限管理 */
// 隐藏收起展开按钮
/deep/ .el-tree-node__expand-icon.expanded{
  display: none;
}
///deep/ .el-tree-node__expand-icon.is-leaf{
//  display: none;
//}
.jurisdiction-content {
  height: calc(100% - 61px);
  position: relative;
  overflow: hidden;

  .content-left {
    height: 100%;
    margin-right: 250px;
    overflow: hidden;
  }
  .content-right {
    width: 250px;
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
  }
  .jurisdiction-box {
    padding-bottom: 15px;
    height: calc(100% - 61px);
    overflow: hidden;
    position: relative;
  }
  .jurisdiction-content-checkbox {
    //height: calc(100% - 47px);
    height: calc(75vh - 180px);
    overflow-y: scroll;
    padding: 0 20px;

    /deep/ .el-tree-node__content:hover {
      background-color: white;
      color: #2362FB;
    }
  }
  .jurisdiction-content-checkbox
  .el-tree
  /deep/
  .el-tree-node
  > .el-tree-node__content {
    margin-bottom: 20px;
    width: 180px;
  }
  .jurisdiction-content-checkbox /deep/ .el-tree .el-tree-node {
    white-space: inherit;
    margin-bottom: 5px;
  }
  .jurisdiction-content-checkbox
  /deep/
  .el-tree
  > .el-tree-node
  > .el-tree-node__children
  > .is-expanded
  > .el-tree-node__children
  > .is-expanded {
    display: inline-block;
  }
  .role-authorization /deep/ .el-tree-node__expand-icon {
    display: none;
  }
  .data-radio {
    padding: 5px 30px;
  }
  .data-radio .el-radio {
    display: block;
    margin: 20px 0;
  }
  .el-tree-node.is-expanded>.el-tree-node__children{
    display: flex;
  }

}
// 功能权限管理end
</style>
